using System;
using System.Text;
using OhioState.Graphics;
using OhioState.Graphics.Proxy;


namespace OhioState.Graphics.OpenGL
{
    public class ShaderRoutineHandler : OpenGLObject, IShaderRoutine, IOpenGLResource, IDisposable
    {
        private ShaderRoutine _shaderProxy;
        public ShaderRoutineHandler(ShaderRoutine proxy) : base(proxy)
        {
            _shaderProxy = proxy;
        }


        #region IShaderRoutine Members

        private bool _created = false;
        private ShaderRoutineGL _realRoutine;
        private bool _compileStatus = false;
        public bool Compile(IRenderPanel panel)
        {
            if (!_created)
            {
                Create();
            }

            _realRoutine.ShaderContent = _shaderProxy.ShaderContent;
            _compileStatus = _realRoutine.Compile(panel);
            SetCompileLog();

            return _compileStatus;
        }

        private void SetCompileLog()
        {
            StringBuilder log = new StringBuilder(1024);
            log.Append("----- " + "Compilation of   ");
            log.Append(_shaderProxy.Name);
            if (_realRoutine.IsCompiled)
                log.AppendLine("   succeeded! -----");
            else
                log.AppendLine("   failed! -----");
            log.AppendLine(_realRoutine.CompileLog);
            _shaderProxy.SetCompileInfo(log.ToString());
        }

        private void Create()
        {
            if (_shaderProxy is VertexShader)
            {
                _realRoutine = new VertexRoutineGL();
            }
            else if (_shaderProxy is FragmentShader)
            {
                _realRoutine = new FragmentRoutineGL();
            }
            else
            {
                throw new Exception("ShaderRoutine does not seem to be valid!");
            }
            _created = true;
            this.Invalid = true;
        }

        public string ShaderContent
        {
            get
            {
                return _shaderProxy.ShaderContent;
            }
            set
            {
                _realRoutine.ShaderContent = value;
                this.Invalid = true;
            }
        }
        #endregion

        #region IHardwareResource<uint> Members
        public uint GUID
        {
            get { return _realRoutine.GUID; }
        }
        #endregion

        #region IDisposable Members
        public override void Dispose()
        {
            base.Dispose();
            Dispose(true);
        }
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_created)
                {
                    _realRoutine.Dispose();
                }
            }
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}
